﻿using DBModel.Context;
using DBModel.Entity;
using ILogicLayer.DTO;
using ILogicLayer.Interface;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Quartz.Xml.JobSchedulingData20;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;

namespace WebApiCoreFx.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[AllowAnonymous]
    public class ValuesController : ControllerBase
    {
        private readonly ILogger<ValuesController> _logger;
        private readonly TestController testCtl;
        private readonly ISqlSugarClient dbClient;
        private readonly AppDBContext dbContext;

        public ValuesController(
            ILogger<ValuesController> logger,
            //TestController testCtl,
            ISqlSugarClient dbClient,
            AppDBContext dbContext
            )
        {
            this._logger = logger;
            //this.testCtl = testCtl;
            this.dbClient = dbClient;
            this.dbContext = dbContext;
        }

        // GET api/values
        [HttpGet]
        //[AllowAnonymous]
        //[MultipleCache]
        public string[] Get()
        {
            return new string[] { $"{Request.Scheme}://{Request.Host}{Request.Path}", $"(MiddlewareTest输入处理:{Request.Headers["TestMiddleware"]})" };
        }

        /// <summary>
        /// ValidateAntiForgeryToken特性(Request.Header包含X-XSRF-TOKEN才能正常请求)
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        [HttpPost]
        [AopDLL.Filter.CustomizeFilter]
        [ValidateAntiForgeryToken]
        public string Post([FromQuery] string value)
        {
            return $"___{value}";
        }

        [HttpGet]
        public async Task<string> EFCoreSqlSugarTest(string orm)
        {
            DateTime start = new DateTime(2023, 8, 1);
            DateTime end = new DateTime(2023, 10, 1);

            #region ef core
            if (string.Equals(orm, "ef core"))
            {
                var query = dbContext.VipInfo;
                var t1 = from q in query.Where(s => s.Start >= start && s.End < end)
                         group q by q.IdNum into g
                         select new
                         {
                             IdNum = g.Key,
                             MaxLevel = g.Max(s => s.VipLevel)
                         };

                var rs = from q1 in t1
                         join q2 in query
                         on q1.IdNum equals q2.IdNum
                         where q2.VipLevel == q1.MaxLevel
                         group q2 by q1.IdNum into g
                         select new
                         {
                             IdNum = g.Key,
                             MaxLevel = g.First().VipLevel,
                             MaxTime = g.OrderByDescending(s => s.End).First().End,
                         };
                var list = await rs.ToListAsync();
                return JsonConvert.SerializeObject(list);
            }
            #endregion

            #region sqlsugar
            else
            {
                dbClient.Open();
                var query = dbClient.Queryable<VipInfo>();
                var t1 = query.Where(s => s.Start >= start && s.End < end)
                    .GroupBy(s => s.IdNum)
                    .Select(s => new
                    {
                        s.IdNum,
                        MaxLevel = SqlFunc.AggregateMax(s.VipLevel)
                    }).MergeTable()
                    .InnerJoin<VipInfo>((a, b) => a.IdNum == b.IdNum && b.VipLevel == a.MaxLevel)
                    .GroupBy((a, b) => a.IdNum)
                    .Select((a, b) => new
                    {
                        a.IdNum,
                        a.MaxLevel,
                        MaxTime = SqlFunc.AggregateMax(b.End)
                    });
                var list = await t1.ToListAsync();
                dbClient.Close();
                return JsonConvert.SerializeObject(list);
            }
            #endregion
        }

    }
}